package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.mapper.DictDataMapper;
import cn.wolfcode.car.base.mapper.UserMapper;
import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private DictDataMapper dictDataMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> items) {
        // 获取集合中最后一个元素（封装了statementId和discountAmount）
        StatementItem statementItem = items.remove(items.size() - 1);
        // 获取结算单id
        Long statementId = statementItem.getStatementId();
        // 通过statementId获取结算单对象，并判断结算单的状态
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        // 状态不为消费中
        if (!Statement.STATUS_CONSUME.equals(statement.getStatus())) {
            throw new BusinessException("该结算单已完成支付，无法修改！");
        }
        // 获取优惠价格
        BigDecimal discountAmount = statementItem.getItemPrice();

        // 删除表中原有的结算单明细
        statementItemMapper.deleteByStatementId(statementId);

        // 结算单总消费额
        BigDecimal totalAmount = new BigDecimal("0.00");
        // 结算单明细总个数
        BigDecimal totalQuantity= new BigDecimal("0");
        // 遍历进行累加
        for (StatementItem item : items) {
            // 添加结算单明细
            statementItemMapper.insert(item);
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            totalQuantity = totalQuantity.add(item.getItemQuantity());
        }

        // 判断优惠价格是否大于总消费金额
        if (discountAmount.compareTo(totalAmount) > 0) {
            throw new BusinessException("优惠价格高于总消费金额，不合理！");
        }

        statement.setTotalAmount(totalAmount);
        statement.setTotalQuantity(totalQuantity);
        statement.setDiscountAmount(discountAmount);

        // 更新结算单中的总消费金额、总消费数量、优惠价格
        statementMapper.updateStatement(statement);
    }

    @Override
    @Transactional
    public void payStatement(Long statementId) {
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        // 判断该结算单的状态是否为消费中
        if (!Statement.STATUS_CONSUME.equals(statement.getStatus())) {
            throw new BusinessException("已支付的结算单无需再支付！");
        }
        // 更新结算单的收款人、状态
        statementMapper.payStatement(statementId, ShiroUtils.getUserId(), Statement.STATUS_PAID);
        Long appointmentId = statement.getAppointmentId();

        // 如果是预约单生成的，则修改状态为已结算
        if (appointmentId != null) {
            appointmentMapper.changeStatus(appointmentId, Appointment.STATUS_SETTLE);
        }
    }

    // 导出结算单
    @Override
    public Workbook exportStatementItem(Long id) {
        /* 获取导出Excel表所需要的信息 */
        // 查询结算单
        Statement statement = statementMapper.selectByPrimaryKey(id);
        // 获取服务类型
        String serviceType = dictDataMapper.selectDictLabel("si_service_catalog",
                statement.getServiceType().toString()).getLabel();
        // 获取收款人
        String payee = userMapper.selectByPrimaryKey(statement.getPayeeId()).getUserName();
        // 创建qo对象，封装进id，用于查询结算单明细
        StatementItemQuery qo = new StatementItemQuery();
        qo.setStatementId(id);
        // 查询结算单明细
        List<StatementItem> statementItems = statementItemMapper.selectForList(qo);

        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("结算单明细");
        // 创建第一行
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("客户姓名：");
        row1.createCell(1).setCellValue(statement.getCustomerName());
        row1.createCell(2).setCellValue("联系方式：");
        row1.createCell(3).setCellValue(statement.getCustomerPhone());
        row1.createCell(4).setCellValue("车牌号码：");
        row1.createCell(5).setCellValue(statement.getLicensePlate());

        // 创建第二行
        Row row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("汽车类型：");
        row2.createCell(1).setCellValue(statement.getCarSeries());
        row2.createCell(2).setCellValue("服务类型：");
        row2.createCell(3).setCellValue(serviceType);
        row2.createCell(4).setCellValue("到店时间：");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String actualArrivalTime = sdf.format(statement.getActualArrivalTime());
        row2.createCell(5).setCellValue(actualArrivalTime);

        // 创建第三行
        Row row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("总消费金额：");
        row3.createCell(1).setCellValue(statement.getTotalAmount().longValue());
        row3.createCell(2).setCellValue("服务项数量：");
        row3.createCell(3).setCellValue(statement.getTotalQuantity().longValue());
        row3.createCell(4).setCellValue("优惠金额：");
        row3.createCell(5).setCellValue(statement.getDiscountAmount().longValue());

        // 创建第四行
        Row row4 = sheet.createRow(3);
        row4.createCell(0).setCellValue("实付价格：");
        row4.createCell(1).setCellValue(statement.getTotalAmount()
                .subtract(statement.getDiscountAmount()).longValue());
        row4.createCell(2).setCellValue("收款人：");
        row4.createCell(3).setCellValue(payee);
        row4.createCell(4).setCellValue("收款时间：");
        String createTime = sdf.format(statement.getCreateTime());
        row4.createCell(5).setCellValue(createTime);

        // 创建第五行
        Row row5 = sheet.createRow(4);
        row5.createCell(0).setCellValue("备注信息：");
        row5.createCell(1).setCellValue(statement.getInfo());

        // 创建第六行，空行
        sheet.createRow(5);
        
        // 创建第七行，服务单项明细标题行
        Row serviceItemTitle = sheet.createRow(6);
        serviceItemTitle.createCell(0).setCellValue("服务项名称");
        serviceItemTitle.createCell(1).setCellValue("服务项价格");
        serviceItemTitle.createCell(2).setCellValue("购买数量");

        Row serviceItemRow;
        int rowNum = 6;
        // 遍历结算单明细
        for (StatementItem statementItem : statementItems) {
            serviceItemRow = sheet.createRow(++rowNum);
            serviceItemRow.createCell(0).setCellValue(statementItem.getItemName());
            serviceItemRow.createCell(1).setCellValue(statementItem.getItemPrice().longValue());
            serviceItemRow.createCell(2).setCellValue(statementItem.getItemQuantity().longValue());
        }
        return workbook;
    }
}
